/**
 * 0042
 *  
 * @Author : roryrywang
 * @DateTime : 2024/8/17 23:14
 */

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    int trap(vector<int> &height) {
        vector<int> st;
        int res = 0;
        for (int i = 0; i < height.size(); ++i) {
            if (st.empty()) st.push_back(i);
            while (!st.empty() && height[i] >= height[st[st.size() - 1]]) {
                if (st.size() > 1) {
                    int l = st.size() - 2, r = st.size() - 1;
                    res += (min(height[i], height[st[l]]) - height[st[r]]) * (i - st[l] - 1);
                }
                st.pop_back();
            }
            st.push_back(i);
        }
        return res;
    }
};

int main() {

    return 0;
}